package com.zone.api.di

import android.content.Context
import android.content.SharedPreferences
import com.zone.api.BuildConfig
import com.zone.core.CoreApplication
import okhttp3.OkHttpClient
import retrofit2.Converter
import retrofit2.Retrofit
import javax.inject.Inject
import javax.inject.Provider
import javax.inject.Singleton

@Singleton
class RetrofitProvider (
    private val converterFactories: MutableMap<Int, Provider<Converter.Factory>>,
    private val okHttpClient: OkHttpClient
) : SharedPreferences.OnSharedPreferenceChangeListener {

    private var retrofit: Retrofit? = null

    init {
        val sharedPreferences = CoreApplication.coreApp.getSharedPreferences("AppConfig", Context.MODE_PRIVATE)
        sharedPreferences.registerOnSharedPreferenceChangeListener(this)
        retrofit = createRetrofit(
            sharedPreferences.getString("BASE_URL", BuildConfig.SERVER_URL)
                ?: BuildConfig.SERVER_URL
        )
    }

    private fun createRetrofit(baseUrl: String): Retrofit {
        val retrofitBuilder = Retrofit.Builder().baseUrl(baseUrl).client(okHttpClient)
        converterFactories.keys.sortedByDescending { it }.forEach {
            converterFactories[it]?.get()?.let { conv ->
                retrofitBuilder.addConverterFactory(conv)
            }
        }
        return retrofitBuilder
            .build()
    }

    fun getRetrofit(): Retrofit {
        return retrofit!!
    }

    override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
        if (key == "BASE_URL") {
            val newBaseUrl = sharedPreferences?.getString("BASE_URL", BuildConfig.SERVER_URL)
                ?: BuildConfig.SERVER_URL
            retrofit = createRetrofit(newBaseUrl)
        }
    }
}
